package com.linkwechat.common.utils;


import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
//wjp
public class UrlUtil {
    /**
     * 获取请求地址中的某个参数
     *
     * @param url
     * @param name
     * @return
     */
    public static String getParam(String url, String name) {
        return urlSplit(url).get(name);
    }

    /**
     * 去掉url中的路径，留下请求参数部分
     *
     * @param url url地址
     * @return url请求参数部分
     */
    private static String truncateUrlPage(String url) {
        String strAllParam = null;
        String[] arrSplit;
        String u = url.trim();
        arrSplit = u.split("[?]");
        if (u.length() > 1) {
            if (arrSplit.length > 1) {
                for (int i = 1; i < arrSplit.length; i++) {
                    strAllParam = arrSplit[i];
                }
            }
        }
        return strAllParam;
    }

    /**
     * 去掉url中的参数，留下请求路径
     *
     * @param url url地址
     * @return url请求路径部分
     */
    public static String truncateUrl(String url) {
        String strinUrl = null;
        String u = url.trim();
        String[] linkArr = u.split("[?]");
        if (linkArr.length > 0) {
            strinUrl = linkArr[0];
        }
        return strinUrl;
    }

    /**
     * 将参数存入map集合
     *
     * @param url url地址
     * @return url请求参数部分存入map集合
     */
    public static Map<String, String> urlSplit(String url) {
        Map<String, String> mapRequest = new HashMap<String, String>();
        String[] arrSplit;
        String strUrlParam = truncateUrlPage(url);
        if (strUrlParam == null) {
            return mapRequest;
        }
        arrSplit = strUrlParam.split("[&]");
        for (String strSplit : arrSplit) {
            String[] arrSplitEqual;
            arrSplitEqual = strSplit.split("[=]");
            //解析出键值
            if (arrSplitEqual.length > 1) {
                //正确解析
                mapRequest.put(arrSplitEqual[0], arrSplitEqual[1]);
            } else {
                if (arrSplitEqual[0] != "") {
                    //只有参数没有值，不加入
                    mapRequest.put(arrSplitEqual[0], "");
                }
            }
        }
        return mapRequest;
    }


    /**
     * <p>功能描述: [拼接url] </p>
     * @param host
     * @param path
     * @param querys key,value形式参数 添加到url上(?传参)
     * @return
     * @throws UnsupportedEncodingException
     * @Title buildUrl
     */
    public static String buildUrl(String host, String path, Map<String, String> querys) {
        try {
            StringBuilder sbUrl = new StringBuilder();
            sbUrl.append(host);
            if (!StringUtil.isEmpty(path)) {
                sbUrl.append(path);
            }
            if (querys == null) {
                return sbUrl.toString();
            }
            StringBuilder sbQuery = new StringBuilder();
            for (Map.Entry<String, String> query : querys.entrySet()) {
                if (0 < sbQuery.length()) {
                    sbQuery.append("&");
                }
                if (StringUtil.isEmpty(query.getKey()) && !StringUtil.isEmpty(query.getValue())) {
                    sbQuery.append(query.getValue());
                }
                if (!StringUtil.isEmpty(query.getKey())) {
                    sbQuery.append(query.getKey());
                    if (!StringUtil.isEmpty(query.getValue())) {
                        sbQuery.append("=");
                        sbQuery.append(URLEncoder.encode(query.getValue(), "utf-8"));
                    }
                }
            }
            if (0 < sbQuery.length()) {
                sbUrl.append("?").append(sbQuery);
            }
            return sbUrl.toString();
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    public static String addParam(String url,String name,String value){
        if(url.contains("?")){
            return url + "&" + name + "=" + value;
        }
        return url + "?" + name + "=" + value;
    }


    /**
     * 获取除去参数的的utl
     * @param url
     * @param parameterSeparator 参数分隔符   一般是？  但是有的页面是以其它符号作为参数分隔的，比如  #
     * @return
     */
    public static String getPrefixUrl(String url,String parameterSeparator ){
        if(StringUtil.isEmpty(parameterSeparator)){
            parameterSeparator = "?";
        }
        return url.substring(0,url.indexOf(parameterSeparator) + parameterSeparator.length());
    }

    /**
     *
     * @param url
     * @param parameterSeparator 参数分隔符   一般是？  但是有的页面是以其它符号作为参数分隔的，比如  #
     * @return
     */
    public static Map<String,String> getUrlParams(String url,String parameterSeparator){
        if(StringUtil.isEmpty(parameterSeparator)){
            parameterSeparator = "?";
        }
        Map<String,String> params = new HashMap<>();
        url = url.substring(url.indexOf(parameterSeparator) + parameterSeparator.length());
        String[] keyValues = url.split("&");
        for(int i = 0; i < keyValues.length; i++){
            String[] arr = keyValues[i].split("=");
            params.put(arr[0],arr.length > 1 ? arr[1] : null);
        }
        return params;
    }

    /**
     *
     * @param url
     * @param parameterSeparator 参数分隔符   一般是？  但是有的页面是以其它符号作为参数分隔的，比如  #
     * @param key
     * @param value
     * @return
     */
    public static String replaceParams(String url,String parameterSeparator,String key,String value){
        Map<String,String> newParams = getUrlParams(url,parameterSeparator);

        newParams.put(key,value);

        return buidUrl(url,parameterSeparator,newParams);
    }

    /**
     *
     * @param url
     * @param parameterSeparator 参数分隔符   一般是？  但是有的页面是以其它符号作为参数分隔的，比如  #
     * @param params
     * @return
     */
    public static String replaceParams(String url,String parameterSeparator,Map<String,String> params){
        Map<String,String> newParams = getUrlParams(url, parameterSeparator);

        for (Map.Entry<String, String> entry : params.entrySet()) {
            String k = entry.getKey();
            String v = entry.getValue();
            newParams.put(k,v);
        }

        return buidUrl(url,parameterSeparator,newParams);
    }

    /**
     *
     * @param url
     * @param parameterSeparator 参数分隔符   一般是？  但是有的页面是以其它符号作为参数分隔的，比如  #
     * @param params
     * @return
     */
    public static String buidUrl(String url,String parameterSeparator,Map<String,String> params){
        String prefix = getPrefixUrl(url, parameterSeparator);

        StringBuilder sb = new StringBuilder(prefix);
        for (Map.Entry<String, String> entry : params.entrySet()) {
            String k = entry.getKey();
            String v = entry.getValue();
            sb.append(k).append("=").append(v == null ? "" : v).append("&");
        }
        url = sb.toString();
        return url.substring(0,url.lastIndexOf("&"));
    }

    //转为正则类型的url
    public static String replaceVariables(String url) {
        if(url.contains("?")) {
            url = url.substring(0, url.lastIndexOf("?"));
        }
        if(url.contains("#")) {
            url = url.substring(0, url.lastIndexOf("#"));
        }
        if(!url.contains("{")){
            return url + "\\/?$";
        }
        String urlTemp = url;
        char[] urls = urlTemp.toCharArray();
        int startCount = 0;
        int endCount = 0;
        int start = 0;
        List<String> replaces = new ArrayList<>();
        for (int i = 0; i < urls.length; i++) {
            if (urls[i] == '{') {
                startCount++;
            }
            if (urls[i] == '{' && startCount == 1) {
                start = i;
            }
            if (urls[i] == '}') {
                endCount++;
            }
            if (startCount == endCount && startCount != 0) {
                String temp = urlTemp.substring(start, i + 1);
                replaces.add(temp);
                startCount = 0;
                endCount = 0;
                start = 0;
            }
        }
        String pvPattern = "[{a-zA-Z0-9._\\-}]+";
        for (String string : replaces) {
            urlTemp = urlTemp.replace(string, pvPattern);
        }
        return urlTemp + "\\/?$";
    }

    public static String urlEncode(String url){
        try {
            return URLEncoder.encode(url, "UTF-8");
        }catch (UnsupportedEncodingException e){
            throw new RuntimeException(e);
        }
    }

    public static String urlDecode(String url){
        try {
            return URLEncoder.encode(url, "UTF-8");
        }catch (UnsupportedEncodingException e){
            throw new RuntimeException(e);
        }
    }

}
